import wepy from 'wepy'

export default class Home extends wepy.mixin {
  data = {
    // 商品id
    goods_id: 0,
    // 商品详情数据
    goods_info: {},
    // 收货地址
    addressInfo: null
  }

  methods = {
    // 预览图片
    previewImg (current) {
      const urls = this.goods_info.pics.map(item=>item.pics_big)
      wepy.previewImage({urls, current})
    },

    // 选择收获地址
    async chooseAddress () {
      // 应该调用微信原生的界面
      const res =  await wepy.chooseAddress().catch(err=>err)
      if(res.errMsg !== 'chooseAddress:ok') return wepy.baseToast('已取消选择地址')
      wepy.baseToast('已选择收货地址')
      this.addressInfo = res 
      wepy.setStorageSync('address',res)
    },

    // 点击加入购物车
    addCarHandle () {
      // 要获取到全局的cart的数据
      // console.log(this.$parent.globalData.cart)
      // 能不能拿到商品的信息：this.goods_info
      const { goods_id, goods_name, goods_price,goods_big_logo } = this.goods_info
      this.$parent.addCart(goods_id, goods_name, goods_price,goods_big_logo)
    }
  }

  // 获取详情的数据
  async getGoodsDetail () {
    const  { data: res } = await wepy.get('/goods/detail',{
      goods_id: this.goods_id
    })
    if(res.meta.status !== 200) return wepy.baseToast()
    this.goods_info = res.message 
    this.$apply()
  }

  computed = {
    // 收货地址
    addressStr () {
      if(this.addressInfo === null) return '请选择收货地址'
      // es6 解构
      const { provinceName, cityName, countyName, userName } = this.addressInfo
      return provinceName+cityName+countyName+userName
    },

    // 计算购物车数量
    cartLength () {
      return this.$parent.globalData.cart.length
    }
  }

  onLoad (options) {
    this.goods_id = options.goods_id
    this.getGoodsDetail()
    this.addressInfo = wepy.getStorageSync('address') || null
  }
}